package imp

import (
	sqlc "bgs/db/sqlc"
	userGrpc "bgs/grpc/gen/service/user"
	"bgs/grpc/gen/shared/message"
	"bgs/grpc/imp/enums"
	userService "bgs/service/user"
	"bgs/util"
	"context"
	"database/sql"
	"fmt"
)

/****************************************************************************************/
/*                               user entity of helper                                  */
/****************************************************************************************/

func transformUserEntityToPb(o sqlc.User) *userGrpc.UserEntity {
	return &userGrpc.UserEntity{
		Id:                   o.ID,
		OpenId:               o.OpenID,
		Mobile:               o.Mobile.String,
		MemberToken:          o.MemberToken.String,
		MemberTokenRefreshed: sqlc.GoNTimeToPBTimestamp(o.MemberTokenRefreshed),
		Pic:                  o.Pic.String,
		NickName:             o.NickName.String,
		RealName:             o.RealName.String,
		IdCardNo:             o.IDCardNo.String,
		Intro:                o.Intro.String,
		HomepageBg:           o.HomepageBg.String,
		Registered:           sqlc.GoTimeToPBTimestamp(o.Registered),
	}
}

func mapUserEntityToPb(list []sqlc.User, f func(sqlc.User) *userGrpc.UserEntity) []*userGrpc.UserEntity {
	r := make([]*userGrpc.UserEntity, len(list))
	for i, item := range list {
		r[i] = f(item)
	}
	return r
}

/****************************************************************************************/
/*                               user entity of cmd                                     */
/****************************************************************************************/

// CreateUser 创建用户
func (s *UserAPIService) CreateUser(ctx context.Context, req *userGrpc.CreateUserRequest) (res *userGrpc.CreateUserResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("userImp->CreateUser:%v", req)
	res = &userGrpc.CreateUserResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	arg := sqlc.CreateUserParams{
		OpenID:       req.OpenId,
		NickName:     sqlc.NSFromString(req.NickName),
		RegisterPage: sqlc.NSFromString(req.RegisterPage),
		UnionID:      sqlc.NSFromString(req.UnionId),
		Roles:        req.Roles,
	}
	user, err := s.dao.Q.CreateUser(ctx, arg)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.User = transformUserEntityToPb(user)
	return
}

// UpdateUserInfo 更新个人信息
func (s *UserAPIService) UpdateUserInfo(ctx context.Context, req *userGrpc.UpdateUserInfoRequest) (res *userGrpc.UpdateUserInfoResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("userImp->UpdateUserInfo:%v", req)
	res = &userGrpc.UpdateUserInfoResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	arg := sqlc.UpdateUserInfoParams{
		ID:         req.Id,
		Pic:        sqlc.NSFromString(req.Pic),
		NickName:   sqlc.NSFromString(req.NickName),
		Intro:      sqlc.NSFromString(req.Intro),
		HomepageBg: sqlc.NSFromString(req.HomepageBg),
	}
	user, err := s.dao.Q.UpdateUserInfo(ctx, arg)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.User = transformUserEntityToPb(user)
	return
}

// UpdateUserMobile 更新用户手机
func (s *UserAPIService) UpdateUserMobile(ctx context.Context, req *userGrpc.UpdateUserMobileRequest) (res *userGrpc.UpdateUserMobileResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("userImp->UpdateUserMobile:%v", req)
	res = &userGrpc.UpdateUserMobileResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	arg := sqlc.UpdateUserMobileParams{
		ID:     req.Id,
		Mobile: sqlc.NSFromString(req.Mobile),
	}
	user, err := s.dao.Q.UpdateUserMobile(ctx, arg)
	if err != nil {
		errCode := s.pgErrorChecker.ExtractCode(ctx, &err)
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		if errCode == "23505" {
			//unique_violation
			err = fmt.Errorf("手机号已被绑定")
		}
		return
	}
	res.User = transformUserEntityToPb(user)
	return
}

// UpdateUserMemberToken 更新用户会员token
func (s *UserAPIService) UpdateUserMemberToken(ctx context.Context, req *userGrpc.UpdateUserMemberTokenRequest) (res *userGrpc.UpdateUserMemberTokenResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("userImp->UpdateUserMemberToken:%v", req)
	res = &userGrpc.UpdateUserMemberTokenResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	arg := sqlc.UpdateUserMemberTokenParams{
		ID:          req.Id,
		MemberToken: sqlc.NSFromString(req.MemberToken),
	}
	user, err := s.dao.Q.UpdateUserMemberToken(ctx, arg)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.User = transformUserEntityToPb(user)
	return
}

/****************************************************************************************/
/*                               user entity of query                                   */
/****************************************************************************************/

// GetUser 获取单个用户
func (s *UserAPIService) GetUser(ctx context.Context, req *userGrpc.GetUserRequest) (res *userGrpc.GetUserResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("userImp->GetUser:%v", req)
	res = &userGrpc.GetUserResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	user, err := s.dao.Q.GetUser(ctx, req.Id)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.User = transformUserEntityToPb(user)
	return
}

// GetUserByOpenID 通过openID获取单个用户
func (s *UserAPIService) GetUserByOpenID(ctx context.Context, req *userGrpc.GetUserByOpenIDRequest) (res *userGrpc.GetUserByOpenIDResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("userImp->GetUserByOpenID:%v", req)
	res = &userGrpc.GetUserByOpenIDResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	user, sqlErr := s.dao.Q.GetUserByOpenID(ctx, req.OpenId)
	if sqlErr != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    util.Int32IfThenElse(sql.ErrNoRows == sqlErr, 404, 400),
			Msg:     sqlErr.Error(),
		}
		return
	}
	res.User = transformUserEntityToPb(user)
	return
}

// GetUserByMobile 通过mobile获取单个用户
func (s *UserAPIService) GetUserByMobile(ctx context.Context, req *userGrpc.GetUserByMobileRequest) (res *userGrpc.GetUserByMobileResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("userImp->GetUserByMobile:%v", req)
	res = &userGrpc.GetUserByMobileResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	user, sqlErr := s.dao.Q.GetUserByMobile(ctx, sqlc.NSFromString(req.Mobile))
	if sqlErr != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    util.Int32IfThenElse(sql.ErrNoRows == sqlErr, 404, 400),
			Msg:     sqlErr.Error(),
		}
		return
	}
	res.User = transformUserEntityToPb(user)
	return
}

// ListUsers 分页获取多个用户
func (s *UserAPIService) ListUsers(ctx context.Context, req *userGrpc.ListUsersRequest) (res *userGrpc.ListUsersResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("userImp->ListUsers:%v", req)

	res = &userGrpc.ListUsersResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	total, err := s.dao.Q.CountUsers(ctx)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}

	if total == 0 {
		// 不用继续调用listfunc
		return
	}

	arg := sqlc.ListUsersParams{
		Limit:  req.Limit,
		Offset: req.Offset,
	}
	users, err := s.dao.Q.ListUsers(ctx, arg)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.Total = total
	res.Users = mapUserEntityToPb(users, transformUserEntityToPb)
	return
}

/****************************************************************************************/
/*                            user_ext entity of helper                                 */
/****************************************************************************************/

func transformUserExtEntityToPb(userExt sqlc.UserExt) *userGrpc.UserExtEntity {
	return &userGrpc.UserExtEntity{
		UserId:      userExt.UserID,
		ShareUserId: sqlc.NInt64ToInt64(userExt.ShareUserID),
		Sex:         userExt.Sex.String,
		City:        userExt.City.String,
		Province:    userExt.Province.String,
		Country:     userExt.Country.String,
	}
}

/****************************************************************************************/
/*                            user_ext entity of cmd                                    */
/****************************************************************************************/

// UpsertUserExt 插入/更新用户扩展信息
func (s *UserAPIService) UpsertUserExt(ctx context.Context, req *userGrpc.UpsertUserExtRequest) (res *userGrpc.UpsertUserExtResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("userImp->UpsertUserExt:%v", req)
	res = &userGrpc.UpsertUserExtResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	arg := sqlc.UpsertUserExtParams{
		UserID:      req.UserId,
		ShareUserID: sqlc.NInt64FromInt64(req.ShareUserId),
		Sex:         sqlc.NSFromString(util.DefaultString(req.Sex, string(enums.GenderUnknown))),
		City:        sqlc.NSFromString(req.City),
		Province:    sqlc.NSFromString(req.Province),
		Country:     sqlc.NSFromString(req.Country),
	}
	userExt, err := s.dao.Q.UpsertUserExt(ctx, arg)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.UserExt = transformUserExtEntityToPb(userExt)
	return
}

/****************************************************************************************/
/*                            user_ext entity of query                                  */
/****************************************************************************************/

// GetUserExtByUserID  获取单个用户扩展信息
func (s *UserAPIService) GetUserExtByUserID(ctx context.Context, req *userGrpc.GetUserExtByUserIDRequest) (res *userGrpc.GetUserExtByUserIDResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("userImp->GetUserExtByUserID:%v", req)
	res = &userGrpc.GetUserExtByUserIDResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	userExt, err := s.dao.Q.GetUserExtByUserID(ctx, req.UserId)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.UserExt = transformUserExtEntityToPb(userExt)
	return
}

/****************************************************************************************/
/*                            user_stat entity of helper                                */
/****************************************************************************************/

func transformUserStatEntityToPb(userStat sqlc.UserStat) *userGrpc.UserStatEntity {
	return &userGrpc.UserStatEntity{
		UserId:               userStat.UserID,
		FansCount:            userStat.FansCount,
		FollowUserCount:      userStat.FollowUserCount,
		FollowBrandCount:     userStat.FollowBrandCount,
		EndorseBrandCount:    userStat.EndorseBrandCount,
		EndorseActivityCount: userStat.EndorseActivityCount,
		InvolveActivityCount: userStat.InvolveActivityCount,
		OrderCount:           userStat.OrderCount,
		ViewCount:            userStat.ViewCount,
		PayAmount:            userStat.PayAmount,
	}
}

/****************************************************************************************/
/*                            user_stat entity of cmd                                   */
/****************************************************************************************/

// UpsertUserStat 插入/更新用户统计信息
func (s *UserAPIService) UpsertUserStat(ctx context.Context, req *userGrpc.UpsertUserStatRequest) (res *userGrpc.UpsertUserStatResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("userImp->UpsertUserStat:%v", req)
	res = &userGrpc.UpsertUserStatResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	arg := sqlc.UpsertUserStatParams{
		UserID:               req.UserId,
		FansCount:            req.FansCount,
		FollowUserCount:      req.FollowUserCount,
		FollowBrandCount:     req.FollowBrandCount,
		EndorseBrandCount:    req.EndorseBrandCount,
		EndorseActivityCount: req.EndorseActivityCount,
		InvolveActivityCount: req.InvolveActivityCount,
		OrderCount:           req.OrderCount,
		ViewCount:            req.ViewCount,
		PayAmount:            req.PayAmount,
	}
	userStat, err := s.dao.Q.UpsertUserStat(ctx, arg)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.UserStat = transformUserStatEntityToPb(userStat)
	return
}

/****************************************************************************************/
/*                            userJoins entity of helper                                */
/****************************************************************************************/

func transformUserWithStatEntityToPb(row sqlc.GetUserWithStatRow) *userGrpc.UserWithStatEntity {
	return &userGrpc.UserWithStatEntity{
		// user
		Id:                   row.ID,
		OpenId:               row.OpenID,
		Mobile:               row.Mobile.String,
		MemberToken:          row.MemberToken.String,
		MemberTokenRefreshed: sqlc.GoNTimeToPBTimestamp(row.MemberTokenRefreshed),
		Pic:                  row.Pic.String,
		NickName:             row.NickName.String,
		Intro:                row.Intro.String,
		HomepageBg:           row.HomepageBg.String,
		Registered:           sqlc.GoTimeToPBTimestamp(row.Registered),
		// user_stat
		FansCount:            row.FansCount,
		FollowUserCount:      row.FollowUserCount,
		FollowBrandCount:     row.FollowBrandCount,
		FollowStoreCount:     row.FollowStoreCount,
		EndorseBrandCount:    row.EndorseBrandCount,
		EndorseStoreCount:    row.EndorseStoreCount,
		EndorseActivityCount: row.EndorseActivityCount,
		InvolveActivityCount: row.InvolveActivityCount,
		OrderCount:           row.OrderCount,
		ViewCount:            row.ViewCount,
		PayAmount:            row.PayAmount,
	}
}

/****************************************************************************************/
/*                            userJoins entity of query                                 */
/****************************************************************************************/

// GetUserWithStat  获取单个用户信息+用户统计信息
func (s *UserAPIService) GetUserWithStat(ctx context.Context, req *userGrpc.GetUserWithStatRequest) (res *userGrpc.GetUserWithStatResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("userImp->GetUserWithStat:%v", req)
	res = &userGrpc.GetUserWithStatResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	userWithStat, err := s.dao.Q.GetUserWithStat(ctx, req.Id)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.UserWithStat = transformUserWithStatEntityToPb(userWithStat)
	return
}

/****************************************************************************************/
/*                            user account of helper                                    */
/****************************************************************************************/

func transformUserAccountInfoEntityToPb(o sqlc.UserAccount) *userGrpc.UserAccountEntity {
	return &userGrpc.UserAccountEntity{
		UserId:           o.UserID,
		AvailableAmount:  o.AvailableAmount,
		PendingAmount:    o.PendingAmount,
		WithdrawedAmount: o.WithdrawedAmount,
	}
}

func transformUserAccountWithdrawApplymentEntityToPb(o sqlc.UserAccountWithdrawApplyment) *userGrpc.UserAccountWithdrawApplymentEntity {
	return &userGrpc.UserAccountWithdrawApplymentEntity{
		Id:         o.ID,
		UserId:     o.UserID,
		Target:     o.Target,
		Applied:    sqlc.GoTimeToPBTimestamp(o.Applied),
		Amount:     o.Amount,
		Remark:     o.Remark,
		ApplyState: o.ApplyState,
	}
}

func mapUserAccountWithdrawApplymentEntityToPb(list []sqlc.UserAccountWithdrawApplyment, f func(sqlc.UserAccountWithdrawApplyment) *userGrpc.UserAccountWithdrawApplymentEntity) []*userGrpc.UserAccountWithdrawApplymentEntity {
	r := make([]*userGrpc.UserAccountWithdrawApplymentEntity, len(list))
	for i, item := range list {
		r[i] = f(item)
	}
	return r
}

/****************************************************************************************/
/*                            user account of cmd                                       */
/****************************************************************************************/

// CreateUserAccountWithdrawApplyment 创建提现申请
func (s *UserAPIService) CreateUserAccountWithdrawApplyment(ctx context.Context, req *userGrpc.CreateUserAccountWithdrawApplymentRequest) (res *userGrpc.CreateUserAccountWithdrawApplymentResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("userImp->CreateUserAccountWithdrawApplyment:%v", req)
	res = &userGrpc.CreateUserAccountWithdrawApplymentResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}

	var userAccountWithdrawApplyment sqlc.UserAccountWithdrawApplyment
	err = s.dao.NewTxRunner().SqlcExecTx(ctx, func(q *sqlc.Queries) (err error) {

		userAccountWithdrawApplyment, err = s.userService.SubmitAccountWithdrawApplyment(ctx, q, userService.SubmitAccountWithdrawApplymentParam{
			UserID:   req.UserId,
			Target:   sqlc.EmWithdrawTarget(req.Target), // 目前仅支持提现到微信零钱
			Amount:   req.Amount,
			RealName: req.RealName,
			IdCardNo: req.IdCardNo,
			Remark:   req.Remark,
		})

		if err != nil {
			return err
		}

		return
	})

	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.UserAccountWithdrawApplyment = transformUserAccountWithdrawApplymentEntityToPb(userAccountWithdrawApplyment)
	return
}

// ListUserAccountWithdrawApplyments 分页获取多条提现记录
func (s *UserAPIService) ListUserAccountWithdrawApplyments(ctx context.Context, req *userGrpc.ListUserAccountWithdrawApplymentsRequest) (res *userGrpc.ListUserAccountWithdrawApplymentsResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("userImp->ListUserAccountWithdrawApplyments:%v", req)

	res = &userGrpc.ListUserAccountWithdrawApplymentsResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	q := s.dao.Q
	userID := req.UserId

	total, err := q.CountUserAccountWithdrawApplymentsByUserID(ctx, userID)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}

	if total == 0 {
		// 不用继续调用listfunc
		return
	}

	userAccountWithdrawApplyments, err := q.ListUserAccountWithdrawApplymentsByUserID(ctx, sqlc.ListUserAccountWithdrawApplymentsByUserIDParams{
		Limit:  req.Limit,
		Offset: req.Offset,
		UserID: userID,
	})
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.Total = total
	res.UserAccountWithdrawApplyments = mapUserAccountWithdrawApplymentEntityToPb(userAccountWithdrawApplyments, transformUserAccountWithdrawApplymentEntityToPb)
	return
}

/****************************************************************************************/
/*                            user account of query                                     */
/****************************************************************************************/

// GetUserAccount  获取用户账户
func (s *UserAPIService) GetUserAccount(ctx context.Context, req *userGrpc.GetUserAccountRequest) (res *userGrpc.GetUserAccountResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("userImp->GetUserAccount:%v", req)
	res = &userGrpc.GetUserAccountResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	q := s.dao.Q
	userID := req.UserId
	userAccount, err := s.userService.GetAccountInfo(ctx, q, userID)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}

	res.UserAccount = transformUserAccountInfoEntityToPb(userAccount)
	return
}

/****************************************************************************************/
/*                            user_account_log entity of helper                        */
/****************************************************************************************/

func transformUserAccountLogEntityToPb(o sqlc.UserAccountLog) *message.AccountLogInfo {
	return &message.AccountLogInfo{
		Id:       o.ID,
		Logged:   sqlc.GoTimeToPBTimestamp(o.Logged),
		Category: o.Category,
		Amount:   o.Amount,
		Subject:  o.Subject,
		ExtInfo:  o.ExtInfo,
	}
}

func mapUserAccountLogEntityToPb(list []sqlc.UserAccountLog, f func(sqlc.UserAccountLog) *message.AccountLogInfo) []*message.AccountLogInfo {
	r := make([]*message.AccountLogInfo, len(list))
	for i, item := range list {
		r[i] = f(item)
	}
	return r
}

/****************************************************************************************/
/*                            user_account_log of query                                */
/****************************************************************************************/

// ListUserAccountLogs  获取用户资金明细
func (s *UserAPIService) ListUserAccountLogs(ctx context.Context, req *userGrpc.ListUserAccountLogsRequest) (res *userGrpc.ListUserAccountLogsResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("userImp->ListUserAccountLogs:%v", req)
	res = &userGrpc.ListUserAccountLogsResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	q := s.dao.Q
	ts := sqlc.PBTimestampToGoTime(req.Ts)
	begin := sqlc.PBTimestampToGoTime(req.Begin)
	end := sqlc.PBTimestampToGoTime(req.End)

	total, err := q.CountUserAccountLogsByUserID(ctx, sqlc.CountUserAccountLogsByUserIDParams{
		Created:  ts,
		Logged:   begin,
		Logged_2: end,
		UserID:   req.UserId,
	})
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}

	if total == 0 {
		// 不用继续调用listfunc
		return
	}

	arg := sqlc.ListUserAccountLogsByUserIDParams{
		Limit:    req.Limit,
		Offset:   req.Offset,
		Created:  ts,
		Logged:   begin,
		Logged_2: end,
		UserID:   req.UserId,
	}
	brandAccountLogs, err := q.ListUserAccountLogsByUserID(ctx, arg)
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.Total = total
	res.AccountLogs = mapUserAccountLogEntityToPb(brandAccountLogs, transformUserAccountLogEntityToPb)
	return
}

// AggrUserAccountLogsToInOut 统计用户资金的收入与支出
func (s *UserAPIService) AggrUserAccountLogsToInOut(ctx context.Context, req *userGrpc.AggrUserAccountLogsToInOutRequest) (res *userGrpc.AggrUserAccountLogsToInOutResponse, err error) {
	slog := s.NewContextLogger(ctx)
	slog.Infof("userImp->AggrUserAccountLogsToInOut:%v", req)

	res = &userGrpc.AggrUserAccountLogsToInOutResponse{
		OpRet: &message.OperationResult{
			Success: true,
			Code:    0,
		},
	}
	q := s.dao.Q

	aggrRet, err := q.AggrUserAccountLogsToInOut(ctx, sqlc.AggrUserAccountLogsToInOutParams{
		Logged:   sqlc.PBTimestampToGoTime(req.Begin),
		Logged_2: sqlc.PBTimestampToGoTime(req.End),
		UserID:   req.UserId,
	})
	if err != nil {
		res.OpRet = &message.OperationResult{
			Success: false,
			Code:    400,
			Msg:     err.Error(),
		}
		return
	}
	res.Income = aggrRet.Income
	res.Outlay = aggrRet.Outlay
	return
}
